#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/16 16:46
# @Author  : Chenmm
# @File    : main.py
# @Software: PyCharm

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from models.models import create_tables, init_roles
from middlewares.redis import create_redis

from routers.user import user_router
from routers.message import message_router
from routers.course import course_router



app = FastAPI(
    debug=True,
    docs_url=None,
    redoc_url=None
)

app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url="/openapi.json",
        title=app.title + " - Swagger UI",
        # oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url='/static/swagger/swagger-ui-bundle.js',
        swagger_css_url='/static/swagger/swagger-ui.css',
        swagger_favicon_url='/static/swagger/favicon.png',
    )


@app.get("/redoc", include_in_schema=False)
async def redoc_html():
    return get_redoc_html(
        openapi_url=app.openapi_url,
        title=app.title + " - ReDoc",
        redoc_js_url="/static/swagger/redoc.standalone.js",
    )




# 每次启动程序都会检查是否要初始化
async def startup_event():
    app.state.redis = await create_redis()
    print("init redis success")
    create_tables()
    print("init database success")
    init_roles()
    print("init roles success")


app.add_event_handler("startup", startup_event)



async def shutdown_event():
    app.state.redis.close()
    await app.state.redis.wait_closed()
    print("redis closed")



app.include_router(user_router, prefix="/user", tags=["users"])
app.include_router(message_router, prefix="/message", tags=["messages"])
app.include_router(course_router, prefix="/course", tags=["courses"])



if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app", port=8000, host="127.0.0.1", reload=True)